package com.kwan.xframe.util;

import com.trello.rxlifecycle4.LifecycleProvider;
import com.trello.rxlifecycle4.LifecycleTransformer;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.trello.rxlifecycle4.android.FragmentEvent;

import org.reactivestreams.Publisher;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.FlowableTransformer;
import io.reactivex.rxjava3.schedulers.Schedulers;


/**
 * Created by goldze on 2017/6/19.
 * 有关Rx的工具类
 */
public class RxLifeUtils {
	/**
	 * 生命周期绑定
	 *
	 * @param lifecycle Activity
	 */
//	public static <T> LifecycleTransformer<T> bindToLifecycle(@NonNull Context lifecycle) {
//		if (lifecycle instanceof LifecycleProvider) {
//			return ((LifecycleProvider) lifecycle).bindToLifecycle();
//		} else {
//			throw new IllegalArgumentException("context not the LifecycleProvider type");
//		}
//	}

	/**
	 * 生命周期绑定
	 *
	 * @param lifecycle Fragment
	 */
	public static <T> LifecycleTransformer<T> bindToFragmentLifecycle(@NonNull LifecycleProvider<FragmentEvent> lifecycle) {
		return lifecycle.bindToLifecycle();
	}

	/**
	 * 生命周期绑定
	 *
	 * @param lifecycle Activity
	 */
	public static <T> LifecycleTransformer<T> bindToActivityLifecycle(@NonNull LifecycleProvider<ActivityEvent> lifecycle) {
		return lifecycle.bindToLifecycle();
	}

	/**
	 * 线程调度器
	 */
//    public static <T>  FlowableTransformer<T> schedulersTransformer() {
//        return new FlowableTransformer() {
//            @Override
//            public Publisher<K> apply(Flowable<T> upstream) {
//                return upstream.subscribeOn(Schedulers.io())
//						.observeOn(AndroidSchedulers.mainThread())
//						.unsubscribeOn(Schedulers.io());;
//            }
//        };
//    }

	public static <T> FlowableTransformer<T, T> schedulersTransformer() {
		return new FlowableTransformer<T, T>() {
			@Override
			public @NonNull Publisher<T> apply(@NonNull Flowable<T> upstream) {
				return upstream.subscribeOn(Schedulers.io())
						.observeOn(AndroidSchedulers.mainThread())
						.unsubscribeOn(Schedulers.io());
			}
		};
	}

	public static <T> FlowableTransformer<T, T> schedulersIOTransformer() {
		return new FlowableTransformer<T, T>() {
			@Override
			public @NonNull Publisher<T> apply(@NonNull Flowable<T> upstream) {
				return upstream.subscribeOn(Schedulers.io())
						.observeOn(Schedulers.io())
						.unsubscribeOn(Schedulers.io());
			}
		};
	}


}
